package com.example.yichuangyun.ui.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yichuangyun.R;
import com.example.yichuangyun.databinding.ItemContactPersonInfoBinding;
import com.example.yichuangyun.databinding.ItemContactWayBinding;
import com.example.yichuangyun.dialog.ContactWayPopWindow;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.model.contacts.ContactPersonModel;
import com.example.yichuangyun.model.contacts.ContactWayModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UiUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("NotifyDataSetChanged")
public class AddContactAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private List<ContactPersonModel> mData;
    private final List<String> sexData = new ArrayList<>();
    private final OnChangeButtonStatusListener onChangeButtonStatusListener;
    private boolean isEdit;
    private int flag;

    public AddContactAdapter(Context context, List<ContactPersonModel> mData, OnChangeButtonStatusListener onChangeButtonStatusListener) {
        this.context = context;
        this.mData = mData;
        this.onChangeButtonStatusListener = onChangeButtonStatusListener;
        sexData.add(context.getString(R.string.sex_boy));
        sexData.add(context.getString(R.string.sex_girl));
        sexData.add(context.getString(R.string.unknown));
    }

    public AddContactAdapter(Context context, List<ContactPersonModel> mData, OnChangeButtonStatusListener onChangeButtonStatusListener, int flag) {
        this.context = context;
        this.mData = mData;
        this.flag = flag;
        this.onChangeButtonStatusListener = onChangeButtonStatusListener;
        sexData.add(context.getString(R.string.sex_boy));
        sexData.add(context.getString(R.string.sex_girl));
        sexData.add(context.getString(R.string.unknown));
    }

    public AddContactAdapter(Context context, List<ContactPersonModel> mData, OnChangeButtonStatusListener onChangeButtonStatusListener, boolean isEdit) {
        this.context = context;
        this.mData = mData;
        this.onChangeButtonStatusListener = onChangeButtonStatusListener;
        this.isEdit = isEdit;
        sexData.add(context.getString(R.string.sex_boy));
        sexData.add(context.getString(R.string.sex_girl));
        sexData.add(context.getString(R.string.unknown));
    }

    public void onRefresh(List<ContactPersonModel> mList) {
        if (mList != null) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.clear();
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    public void addData(List<ContactPersonModel> mList) {
        if (mList != null && mList.size() != 0) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemContactPersonInfoBinding itemContactPersonInfoBinding = ItemContactPersonInfoBinding.inflate(LayoutInflater.from(context), parent, false);
        return new MyViewHolder(itemContactPersonInfoBinding);
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        if (holder instanceof MyViewHolder) {
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            ContactPersonModel model = mData.get(position);
            myViewHolder.binding.llContactPerson.setBackgroundResource(position == 0 ? R.drawable.shape_time_bg_sel : R.drawable.shape_bg_c6cdd4);
            myViewHolder.binding.icon.setImageResource(position == 0 ? R.mipmap.icon_add_number : R.mipmap.icon_shanchu);
            myViewHolder.binding.tvText.setText(position == 0 ? context.getString(R.string.add_contact_person) : context.getString(R.string.delete_contact_person));
            myViewHolder.binding.tvText.setTextColor(position == 0 ? 0xFF426FFF : 0xFFBBC2CB);
            myViewHolder.binding.ivDefault.setImageResource(model.getIsDef() == 1 ? R.mipmap.icon_open : R.mipmap.icon_close);
            if (model.getSex() != 0) {
                myViewHolder.binding.tvSex.setText(model.getSex() == 1 ? context.getString(R.string.sex_boy) : model.getSex() == 2 ? context.getString(R.string.sex_girl) : context.getString(R.string.unknown));
            } else {
                myViewHolder.binding.tvSex.setText("");
            }
            // 增加/删除联系人
            myViewHolder.binding.llContactPerson.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                if (position == 0) {
                    mData.add(new ContactPersonModel());
                } else {
                    mData.remove(model);
                    if (model.getIsDef() == 1) {
                        mData.get(0).setIsDef(1);
                    }
                }
                notifyDataSetChanged();
                onChangeButtonStatusListener.onChangeListener(mData);
            });

            myViewHolder.binding.rlSex.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                SinglePickerView singlePickerView = new SinglePickerView((Activity) context, context.getString(R.string.sex), sexData) {
                    @Override
                    public void confirm(String label, int position1) {
                        // 性别：1男，2女，3未知
                        int sex = label.equals(context.getString(R.string.sex_boy)) ? 1 : label.equals(context.getString(R.string.sex_girl)) ? 2 : 3;
                        model.setSex(sex);
                        notifyItemChanged(position);
                        onChangeButtonStatusListener.onChangeListener(mData);
                    }
                };
                singlePickerView.showSinglePickerView();
            });

            // 默认联系人
            myViewHolder.binding.ivDefault.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                if (isEdit) {
                    ToastHelper.show(context.getString(R.string.default_and_number_cannot_edit));
                    return;
                }
                if (model.getIsDef() != 1) {
                    for (ContactPersonModel mModel : mData) {
                        mModel.setIsDef(0);
                    }
                    model.setIsDef(1);
                    notifyDataSetChanged();
                }
            });

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (myViewHolder.binding.etName.getTag() instanceof TextWatcher) {
                myViewHolder.binding.etName.removeTextChangedListener((TextWatcher) (myViewHolder.binding.etName.getTag()));
            }

            // 第2步：移除TextWatcher之后，设置EditText的Text。
            myViewHolder.binding.etName.setText(model.getName());

            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    model.setName(TextUtils.isEmpty(editable.toString().trim()) ? "" : editable.toString());
                    onChangeButtonStatusListener.onChangeListener(mData);
                }
            };
            myViewHolder.binding.etName.addTextChangedListener(watcher);
            myViewHolder.binding.etName.setTag(watcher);

            myViewHolder.binding.recyclerView.setAdapter(new ContactWayAdapter(mData.get(position).getTels(), model.getIsDef()));
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        ItemContactPersonInfoBinding binding;

        public MyViewHolder(ItemContactPersonInfoBinding itemContactPersonInfoBinding) {
            super(itemContactPersonInfoBinding.getRoot());
            binding = itemContactPersonInfoBinding;
        }
    }


    class ContactWayAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final List<ContactWayModel> contactWayData;
        private int isDefault;

        public ContactWayAdapter(List<ContactWayModel> contactWayData, int isDefault) {
            this.contactWayData = contactWayData;
            this.isDefault = isDefault;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemContactWayBinding itemContactWayBinding = ItemContactWayBinding.inflate(LayoutInflater.from(context), parent, false);
            return new ContactWayViewHolder(itemContactWayBinding);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            if (holder instanceof ContactWayViewHolder) {
                ContactWayViewHolder contactWayViewHolder = (ContactWayViewHolder) holder;
                ContactWayModel model = contactWayData.get(position);
                if (flag == 1) {
                    contactWayViewHolder.binding.etInfo.setEnabled(model.getIsDefault() != 1);
                    contactWayViewHolder.binding.etInfo.setTextColor(model.getIsDefault() == 1
                            ? context.getColor(R.color.color_BBC2CB) : context.getColor(R.color.color_444444));
                } else {
                    contactWayViewHolder.binding.etInfo.setEnabled(isDefault != 1 || !isEdit || position != 0);
                    contactWayViewHolder.binding.etInfo.setTextColor(isDefault == 1 && isEdit && position == 0
                            ? context.getColor(R.color.color_BBC2CB) : context.getColor(R.color.color_444444));
                }
                contactWayViewHolder.binding.ivAddInfo.setBackgroundResource(position == 0 ? R.drawable.shape_add_number : R.drawable.shape_del_bg_bbc2cb);
                contactWayViewHolder.binding.ivAddInfo.setImageResource(position == 0 ? R.mipmap.icon_add_write : R.mipmap.icon_reduce_write);
                contactWayViewHolder.binding.tvStar.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
                contactWayViewHolder.binding.ivDown.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
                contactWayViewHolder.binding.line.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
                contactWayViewHolder.binding.tvContactWay.setText(UiUtils.getContactTypeName(model.getType()));

                contactWayViewHolder.binding.ivAddInfo.setOnClickListener(v -> {
                    CommonUtil.closeKeyboard((Activity) context);
                    if (position == 0) {
                        contactWayData.add(new ContactWayModel(1));
                    } else {
                        contactWayData.remove(model);
                    }
                    notifyDataSetChanged();
                    onChangeButtonStatusListener.onChangeListener(mData);
                });

                contactWayViewHolder.binding.rlContactWay.setEnabled(position != 0);
                contactWayViewHolder.binding.rlContactWay.setOnClickListener(v -> {
                    CommonUtil.closeKeyboard((Activity) context);
                    ContactWayPopWindow popWindow = new ContactWayPopWindow(context) {
                        @Override
                        public void sure(String type) {
                            if (!type.equals(contactWayViewHolder.binding.tvContactWay.getText().toString())) {
                                contactWayViewHolder.binding.etInfo.setText("");
                                model.setInfo("");
                            }
                            if (type.equals(context.getString(R.string.phone_num))) {
                                model.setType(1);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                            } else if (type.equals(context.getString(R.string.we_chat))) {
                                model.setType(2);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_TEXT);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                            } else if (type.equals(context.getString(R.string.qq))) {
                                model.setType(3);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
                            } else if (type.equals(context.getString(R.string.email))) {
                                model.setType(4);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                            } else if (type.equals(context.getString(R.string.landline))) {
                                model.setType(5);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});
                            }
                            contactWayViewHolder.binding.tvContactWay.setText(type);
                            onChangeButtonStatusListener.onChangeListener(mData);
                        }
                    };
                    popWindow.showPopupWindow(contactWayViewHolder.binding.tvContactWay);
                });

                //1、为了避免TextWatcher在第2步被调用，提前将他移除。
                if (contactWayViewHolder.binding.etInfo.getTag() instanceof TextWatcher) {
                    contactWayViewHolder.binding.etInfo.removeTextChangedListener((TextWatcher) (contactWayViewHolder.binding.etInfo.getTag()));
                }

                switch (model.getType()) {
                    case 1:
                        contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                        contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                        break;
                    case 2:
                        contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_TEXT);
                        contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                        break;
                    case 3:
                        contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                        contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
                        break;
                    case 4:
                        contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                        contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                        break;
                    case 5:
                        contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                        contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});
                        break;
                }
                // 第2步：移除TextWatcher之后，设置EditText的Text。
                contactWayViewHolder.binding.etInfo.setText(model.getInfo());

                TextWatcher watcher = new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        model.setType(UiUtils.getContactType(contactWayViewHolder.binding.tvContactWay.getText().toString()));
                        model.setInfo(TextUtils.isEmpty(editable.toString()) ? "" : editable.toString());
                        onChangeButtonStatusListener.onChangeListener(mData);
                    }
                };
                contactWayViewHolder.binding.etInfo.addTextChangedListener(watcher);
                contactWayViewHolder.binding.etInfo.setTag(watcher);

                contactWayViewHolder.binding.etInfo.setOnFocusChangeListener((v, hasFocus) -> {
                    if (!hasFocus) {
                        switch (model.getType()) {
                            case 1:
                                if (model.getInfo() != null) {
                                    if (model.getInfo().length() < 11 || !model.getInfo().startsWith("1")) {
                                        ToastHelper.show(context.getString(R.string.please_input_correct_phone));
                                        return;
                                    }
                                }
                                break;
                            case 4:
                                if (!CommonUtil.isEmail(contactWayViewHolder.binding.etInfo.getText().toString())) {
                                    ToastHelper.show(context.getString(R.string.please_input_correct_email));
                                    contactWayViewHolder.binding.etInfo.setText("");
                                }
                                break;
                        }
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return contactWayData.size();
        }

        class ContactWayViewHolder extends RecyclerView.ViewHolder {

            ItemContactWayBinding binding;

            public ContactWayViewHolder(ItemContactWayBinding itemContactWayBinding) {
                super(itemContactWayBinding.getRoot());
                binding = itemContactWayBinding;
            }
        }
    }

    public interface OnChangeButtonStatusListener {
        void onChangeListener(List<ContactPersonModel> list);
    }
}
